<template>
  <div class="content">
    <div class="pageSearchView">
      <el-form :inline="true" :model="searchParam" class="demo-form-inline">
        <el-form-item label="供应商">
          <el-select v-model="searchParam.supplierId" placeholder="请选择" clearable style="width: 200px">
            <el-option v-for="(item, index) in supplierList" :key="item.id" :value="item.id"
                       :label="item.name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="仓库">
          <el-select v-model="searchParam.warehouseId" placeholder="请选择" clearable style="width: 200px" @change="searchWarehouseChange">
            <el-option v-for="item in wareList" :key="item.id" :label="item.warehouseName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="库位">
          <el-select v-model="searchParam.storageId" placeholder="请选择" clearable style="width: 200px" :disabled="!searchParam.warehouseId">
            <el-option v-for="item in searchStorageList" :key="item.id" :label="item.storageName"
                       :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="getList()">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="pageTableView">
      <div class="pageTableMenuView">
        <div class="pageTableTitle">
          <div>列表信息</div>
        </div>
        <div class="pageTableButView">
          <el-button @click="doOutIn()" :icon="Files">出库</el-button>
          <el-button @click="handleAdd" :icon="Plus">新建</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <el-table :data="paginatedData" height="calc(100vh - 320px)" row-key="id" :stripe="false"
                header-cell-class-name="witheTableHeader" @expand-change="handleExpandChange">
        <el-table-column type="expand">
          <template #default="scope">
            <!-- 子级列表 -->
            <div m="4">
              <el-table ref="tableCil" :stripe="false" border size="small" :data="scope.row.children"
                        style="width: 95%;margin-left: 20px" header-cell-class-name="blueTableHeader"
                        @selection-change="(e)=>{handleSelectionChange(e,scope.row)}">
                <el-table-column type="selection" width="60" align="center" :selectable="selectable"></el-table-column>
                <el-table-column type="index" width="80" label="" align="center" />
                <el-table-column label="物料名称" prop="materialName" min-width="150" align="center"
                                 show-overflow-tooltip />
                <el-table-column type label="数量" prop="count" min-width="150" align="center"
                                 show-overflow-tooltip />
                <el-table-column type label="状态" prop="type" :formatter="formatType" min-width="150"
                                 align="center" show-overflow-tooltip />
              </el-table>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="序号" align="center" width="70">
          <template #default="scope"> {{ (currentPage - 1) * pageSize + scope.$index + 1 }}</template>
        </el-table-column>
        <el-table-column label="工厂/车间" prop="organizationName" min-width="150" show-overflow-tooltip
                         align="center" />
        <el-table-column label="供应商" prop="supplierName" min-width="150" show-overflow-tooltip align="center" />
        <el-table-column label="库位" prop="storageName" min-width="100" show-overflow-tooltip align="center" />
        <el-table-column label="备注" prop="remark" min-width="100" show-overflow-tooltip align="center" />
        <el-table-column label="创建时间" prop="createTime" min-width="150" show-overflow-tooltip align="center" />
      </el-table>
      <div class="pagePagination">
        <el-pagination background layout="sizes, prev,pager, next,total" :total="pageTotal" :page-size="pageSize"
                       :current-page="currentPage" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </div>
    <!-- 编辑/新建弹框 -->
    <el-dialog v-model="showCrud" :title="crudTitle + '备件出库 '" width="1000px">
      <el-form ref="formRef" :model="formData" label-width="100px" :rules="outInRules">
        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item label="工厂/车间" style="width: 250px" prop="organizationId">
              <el-tree-select v-model="formData.organizationId" :data="workRoomList" check-strictly
                              :props="{ children: 'sonList', label: 'orgName', value: 'id' }" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="供应商" style="width: 250px" prop="supplierId">
              <el-select v-model="formData.supplierId" placeholder="请选择" clearable>
                <el-option v-for="(item, index) in supplierList" :key="item.id" :value="item.id"
                           :label="item.name">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="入库仓库">
              <el-tree-select v-model="formData.targetWarehouseId" :data="wareList" check-strictly
                              :render-after-expand="false" :props="{
									children: 'sonList',
									label: 'warehouseName',
									value: 'id',
								}" @change="formWarehouseChange" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="库位" prop="storageId">
              <el-select v-model="formData.storageId" placeholder="请选择" clearable filterable
                         style="width: 400px" :disabled="!formData.targetWarehouseId">
                <el-option v-for="item in formStorageList" :key="item.id" :label="item.storageName"
                           :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="18">
            <el-form-item label="备注">
              <el-input v-model="formData.remark" style="width: 700px" :rows="3" type="textarea"
                        placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <div class="pageTableTitle">物料列表</div>
        </el-row>
        <el-row :gutter="10" style="padding: 10px">
          <el-table :data="formData.childrenList" style="width:100% " height="300px">
            <el-table-column label="序号" type="index" align="center" width="80" />
            <el-table-column prop="materialId" label="物料编码" align="center">
              <template #default="scope">
                <el-select v-model="scope.row.materialId" :disabled="popType == 1" placeholder=""
                           clearable filterable>
                  <el-option v-for="item in materiaList" :key="item.value" :label="item.label"
                             :value="item.value" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="count" label="数量" align="center">
              <template #default="scope">
                <el-input v-model="scope.row.count" type="number" :disabled="popType == 1"
                          placeholder=""></el-input>
              </template>
            </el-table-column>

            <el-table-column align="center" width="110" fixed="right">
              <template #header>
                <el-button :icon="Plus" text @click="handleAddConfigLine">新建</el-button>
              </template>
              <template #default="scope">
                <el-button type="danger" text :icon="Delete" @click="handleConfigDelete(scope.$index)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
      </el-form>
      <template #footer>
				<span class="dialog-footer">
					<el-button @click="showCrud = false">取消</el-button>
					<el-button type="primary" @click="handleSave(formRef)">保存</el-button>
				</span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, watch, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axiosInstance from '@/utils/http/api';
import {
  Delete, Edit, Tickets, DocumentChecked,
  Search, Share, Upload, Refresh, Plus, DocumentCopy, Files
} from '@element-plus/icons-vue';
import type { FormInstance, FormRules } from 'element-plus';

const paginatedData = ref([]);
const pageSize = ref(10);
const currentPage = ref(1);
const searchParam = ref({});
const wareList = ref([]); // 仓库列表
const searchStorageList = ref([]); // 搜索条件的库位列表
const formStorageList = ref([]); // 表单中的库位列表

const handleSizeChange = (val) => {
  pageSize.value = val;
  getList();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  getList();
};

const selectable = (row) => {
  if (row.type == 3) {
    return false;
  }
  return true;
};

const formatType = (row, column, cellValue) => {
  const typeMap = {
    0: '新建',
    1: '入库',
    2: '领用',
    3: '出库'
  };
  return typeMap[cellValue] || '';
};

const formData = ref({
  planNo: '',
  name: '',
  planBeginTime: null,
  planEndTime: null,
  actualBeginTime: null,
  actualEndTime: null,
  organizationId: '',
  status: '0',
  type: '0'
});

const crudTitle = computed(() => {
  if (popType.value === 1) {
    return '查看';
  } else {
    return isEdit.value ? '编辑' : '新建';
  }
});

// 重置搜索条件
const resetSearch = () => {
  searchParam.value = {
    supplierId: undefined,
    warehouseId: undefined,
    storageId: undefined
  };
  searchStorageList.value = [];
  currentPage.value = 1;
  getList();
};

// 搜索条件仓库变化
const searchWarehouseChange = (warehouseId) => {
  if (!warehouseId) {
    searchStorageList.value = [];
    searchParam.value.storageId = undefined;
    return;
  }

  axiosInstance.post('/api/basedataStorage/listByPojoPage', {
    warehouseId: warehouseId,
    current: 1,
    pageSize: 999999
  })
      .then((res) => {
        if (res.code !== 200) {
          ElMessage.warning(res.message);
          return false;
        }
        searchStorageList.value = res.data.records;
        // 如果当前选中的库位不在新列表中，则清空
        if (searchParam.value.storageId && !searchStorageList.value.some(item => item.id === searchParam.value.storageId)) {
          searchParam.value.storageId = undefined;
        }
      });
};

// 表单仓库变化
const formWarehouseChange = (warehouseId) => {
  if (!warehouseId) {
    formStorageList.value = [];
    formData.value.storageId = undefined;
    return;
  }

  axiosInstance.post('/api/basedataStorage/listByPojoPage', {
    warehouseId: warehouseId,
    current: 1,
    pageSize: 999999
  })
      .then((res) => {
        if (res.code !== 200) {
          ElMessage.warning(res.message);
          return false;
        }
        formStorageList.value = res.data.records;
        // 如果当前选中的库位不在新列表中，则清空
        if (formData.value.storageId && !formStorageList.value.some(item => item.id === formData.value.storageId)) {
          formData.value.storageId = undefined;
        }
      });
};

const materiaList = ref([]);
const formRef = ref(null);
const outInRules = reactive<FormRules<formRef>>({
  organizationId: [
    { required: true, message: '请选择工厂/车间', trigger: 'blur' }
  ],
  supplierId: [
    { required: true, message: '请选择供应商', trigger: 'blur' }
  ],
  storageId: [
    { required: true, message: '请选择库位', trigger: 'blur' }
  ]
});

const handleAddConfigLine = () => {
  formData.value.childrenList.push({
    materialId: null,
    materialCount: null,
    batchNo: null
  });
};

const handleSelectionChange = (e, row) => {
  const dataPage = paginatedData.value.map(item => {
    if (item.id === row.id) {
      return { ...item, childCheck: e };
    }
    return item;
  });
  paginatedData.value = dataPage;
};

const doOutIn = () => {
  ElMessageBox.confirm(
      '是否出库？',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
  )
      .then(async () => {
        const checkItem = [];
        paginatedData.value.map(item => {
          if (item.childCheck) {
            const ids = item.childCheck.map(i => {
              return {
                id: i.id,
                type: 3,
                count: i.count,
              }
            });
            checkItem.push(...ids);
          }
        });

        if (checkItem.length === 0) {
          ElMessage.warning('请至少选择一条记录');
          return;
        }

        axiosInstance.post('/api/sparePartDetail/updateTypeBatch', checkItem)
            .then(res => {
              if (res.code !== 200) {
                ElMessage.error(res.message);
                return false;
              }
              ElMessage.success('出库成功');
              getList();
            });
      });
};

const handleConfigDelete = (e) => {
  formData.value.childrenList.splice(e, 1);
};

const workRoomList = ref([]); // 车间
const supplierList = ref([]);

const getOption = () => {
  // 获取仓库列表
  axiosInstance.get('/api/basedataWarehouse/treeList', {}).then(res => {
    if (res.code !== 200) {
      ElMessage.error(res.message);
      return false;
    }
    wareList.value = res.data;
  });

  // 获取供应商列表
  axiosInstance.post(`/api/basedataSupplier/getPage`, {
    current: 1,
    pageSize: 20
  }).then(res => {
    if (res.code == 200) {
      supplierList.value = res.data.records;
    }
  });

  // 获取车间列表
  axiosInstance.post('/api/basedataOrganization/getAll', {})
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        workRoomList.value = res.data;
      });

  // 获取物料列表
  axiosInstance.post('/api/basedataMaterial/getAll', {}).then(res => {
    if (res.code == 200) {
      const list = res.data;
      const loop = [];
      for (const item of list) {
        loop.push(
            {
              value: item.id,
              label: item.materialName
            }
        );
      }
      materiaList.value = loop;
    }
  });
};

const isEdit = ref(false); // 是否编辑
const showCrud = ref(false); // 编辑/新建弹框

// 新建记录
const handleAdd = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  popType.value = 0;
  isEdit.value = false;
  formData.value = {
    childrenList: [{
      materialId: null,
      materialCount: null,
      batchNo: null
    }]
  };
  showCrud.value = true;
};

const popType = ref(0); // 0 编辑 1 只读

// 保存记录
const handleSave = async (formEl: FormInstance | undefined) => {
  await formEl.validate((valid, fields) => {
    if (valid) {
      const param = {
        ...formData.value,
        status: 3,
      };
      axiosInstance.post('/api/sparePart/save', param)
          .then((res) => {
            if (res.code !== 200) {
              ElMessage.error(res.message);
              return false;
            }
            showCrud.value = false;
            getList();
          });
    }
  });
};

const handleExpandChange = (row: any, expandedRows: any[]) => {
  if (expandedRows.includes(row)) {
    rowChildren(row);
  } else {
    // getList();
  }
};

const rowChildren = (row: any) => {
  axiosInstance.post('/api/sparePartDetail/getAll', { sparePartId: row.id }).then(res => {
    if (res.code !== 200) {
      ElMessage.warning(res.message);
      return false;
    }
    const listGroup = paginatedData.value.map((item) => {
      if (item.id === row.id) {
        return { ...item, children: res.data };
      }
      return item;
    });
    paginatedData.value = listGroup;
  });
};

const pageTotal = ref(0);

// 获取列表
const getList = async () => {
  paginatedData.value = [];
  const params = {
    ...searchParam.value,
    current: currentPage.value,
    pageSize: pageSize.value,
    status: 3,
  };

  // 如果只选择了仓库没选库位，删除storageId参数
  if (params.warehouseId && !params.storageId) {
    delete params.storageId;
  }

  axiosInstance.post('/api/sparePart/getPage', params)
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        paginatedData.value = res.data.records.map((item) => ({
          ...item,
          children: [],
          layer: 1,
          _loading: false
        }));
        pageTotal.value = res.data.total;
      });
};

onMounted(() => {
  getList();
  getOption();
});
</script>

<style scoped lang="scss"></style>